<?php

namespace app\services\product\product;

use app\dao\product\product\StoreProductTemplateRelationDao;
use app\services\BaseServices;
use crmeb\exceptions\AdminException;

class StoreProductTemplateRelationServices extends BaseServices
{


    public function __construct(StoreProductTemplateRelationDao $dao)
    {
        $this->dao = $dao;
    }


    /**
     *
     * 维护商品模板
     *
     * @param int $product_id
     * @param int $template_id
     * @param array $template_merchant_params_relation
     * @return true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function saveProductTemplateRelation(int $product_id, int $template_id, array $template_merchant_params_relation)
    {
        if (!$template_id) throw new AdminException(30011);
        $template_services = app()->make(StoreProductTemplateServices::class);
        $template = $template_services->get($template_id);
        if (!$template) throw new AdminException(30012);
        if (empty($template_merchant_params_relation)) throw new AdminException(30013);

        foreach ($template_merchant_params_relation as $item) {

            if (!isset($item['merchant_param_key']) || $item['merchant_param_key'] == '') throw new AdminException(30014);
            if (!isset($item['merchant_param_value']) || $item['merchant_param_value'] == '') throw new AdminException(30015);

            // 查找关联关系
            $template_relation = $this->dao->getOne([
                'product_id' => $product_id,
                'template_id' => $template_id,
                'merchant_param_key'    =>  $item['merchant_param_key']
            ]);

            if ($template_relation) {
                $res = $this->dao->update($template_relation->id, ['merchant_param_value' => $item['merchant_param_value']]);
            } else {
                $res = $this->dao->save([
                    'product_id' => $product_id,
                    'template_id' => $template_id,
                    'merchant_param_key'    =>  $item['merchant_param_key'],
                    'merchant_param_value' => $item['merchant_param_value']
                ]);
            }

            if (!$res) throw new AdminException(30016);

        }

        return true;
    }

    public function getProductTemplateRelationInfo($product_id)
    {
        $template_merchant_params_relation = $this->dao->getProductParamsRelation($product_id);

        $template_id = $this->dao->getColumn(['product_id' => $product_id], 'template_id')[0] ?? 0;

        return compact('template_merchant_params_relation', 'template_id');

    }
}